import sys
import tkinter as tk
from PIL import Image, ImageTk
import os


class TkinterImageViewer:
    def __init__(self, root, image_path=None):
        self.root = root
        self.root.overrideredirect(True)  # 无边框窗口
        self.root.attributes('-topmost', True)  # 窗口置顶

        # 初始化变量
        self.image_path = image_path
        self.scale_factor = 1.0
        self.is_dragging = False
        self.drag_position = (0, 0)
        self.start_position = (0, 0)
        self.image = None
        self.photo = None

        # 创建画布（无背景色）
        self.canvas = tk.Canvas(root, highlightthickness=0)
        self.canvas.pack(fill=tk.BOTH, expand=True)

        # 绑定事件
        self.canvas.bind("<Button-1>", self.on_mouse_press)
        self.canvas.bind("<B1-Motion>", self.on_mouse_move)  # 使用用户提供的拖动代码
        self.canvas.bind("<ButtonRelease-1>", self.on_mouse_release)
        self.canvas.bind("<MouseWheel>", self.on_mouse_wheel)  # 滚轮缩放
        self.canvas.bind("<Button-4>", self.on_mouse_wheel)  # Linux滚轮上
        self.canvas.bind("<Button-5>", self.on_mouse_wheel)  # Linux滚轮下
        self.root.bind("<Button-3>", self.on_right_click)  # 右键退出
        self.root.bind("<Escape>", self.on_escape)  # ESC键退出

        # 加载图片
        if image_path and os.path.exists(image_path):
            self.load_image(image_path)
        else:
            self.create_default_image()

        self.root.focus_set()

    def load_image(self, image_path):
        """加载图片文件"""
        try:
            # 处理Windows路径
            image_path = image_path.replace("\\", "/")
            self.image = Image.open(image_path)
            self.scale_factor = 1.0
            self.update_image()

            # 设置初始窗口大小
            width, height = self.image.size
            self.root.geometry(f"{width}x{height}")
        except Exception as e:
            print(f"加载图片失败: {str(e)}")
            self.create_default_image()

    def create_default_image(self):
        """创建默认图片"""
        self.image = Image.new('RGB', (400, 300), color='white')
        self.scale_factor = 1.0
        self.update_image()
        self.root.geometry("400x300")

    def update_image(self):
        """更新缩放后的图片显示"""
        if self.image:
            # 应用缩放因子
            width = int(self.image.width * self.scale_factor)
            height = int(self.image.height * self.scale_factor)

            # 调整图片大小
            resized_image = self.image.resize((width, height), Image.LANCZOS)
            self.photo = ImageTk.PhotoImage(resized_image)

            # 清除画布并显示新图片
            self.canvas.delete("all")
            self.canvas.create_image(0, 0, anchor=tk.NW, image=self.photo)

            # 调整窗口大小
            self.root.geometry(f"{width}x{height}")

    def on_mouse_press(self, event):
        """鼠标按下事件"""
        self.is_dragging = True
        self.drag_position = (event.x_root, event.y_root)
        self.start_position = (self.root.winfo_x(), self.root.winfo_y())

    def on_mouse_move(self, event):
        """处理鼠标移动事件 - 使用您提供的代码"""
        if self.is_dragging:
            dx = event.x_root - self.drag_position[0]
            dy = event.y_root - self.drag_position[1]
            new_x = self.start_position[0] + dx
            new_y = self.start_position[1] + dy
            self.root.geometry(f"+{new_x}+{new_y}")

    def on_mouse_release(self, event):
        """鼠标释放事件"""
        self.is_dragging = False

    def on_mouse_wheel(self, event):
        """鼠标滚轮缩放"""
        # Windows滚轮事件
        if hasattr(event, 'delta'):
            if event.delta > 0:
                self.scale_factor *= 1.1
            else:
                self.scale_factor = max(0.1, self.scale_factor / 1.1)
        # Linux滚轮事件
        else:
            if event.num == 4:  # 上滚
                self.scale_factor *= 1.1
            elif event.num == 5:  # 下滚
                self.scale_factor = max(0.1, self.scale_factor / 1.1)

        self.update_image()

    def on_right_click(self, event):
        """右键点击退出"""
        self.root.destroy()

    def on_escape(self, event):
        """ESC键退出"""
        self.root.destroy()



def posted_img(image_path):
    # 创建主窗口
    root = tk.Tk()
    root.title("纯Tkinter无框图片查看器")
    # 创建图片查看器
    app = TkinterImageViewer(root, image_path)
    root.mainloop()


if __name__ == "__main__":
    # 创建主窗口
    root = tk.Tk()
    root.title("纯Tkinter无框图片查看器")

    # 图片路径（替换为您的实际图片路径）
    image_path = None
    if len(sys.argv) > 1:
        image_path = ' '.join(sys.argv[1:])
    else:
        # 默认图片路径
        image_path = 'C:\\Users\\v_ygyonxiao\\.clipboard_helper\\images\\-8317337897608932924.png'

    # 创建图片查看器
    app = TkinterImageViewer(root, image_path)
    root.mainloop()
